package branch;

import fileoperation.FileCreation;
import gitobject.GitObject;
import repository.Repository;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Branch {
    public String branchName = "master";
    public String commitID;

    /**
     * Constructor
     * @param branchName
     * @param commitID
     */
    public Branch(String branchName, String commitID) throws IOException {
        String path = Repository.getGitDir() + File.separator + "refs" +File.separator + "heads";
        this.branchName = branchName;
        this.commitID = commitID;
        FileCreation.createFile(path, branchName, commitID);
    }

    public Branch(String branchName) throws IOException {
        String path = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
        this.branchName = branchName;
        File currBranchFile = new File(path + File.separator + branchName);
        commitID = GitObject.getValue(currBranchFile);
    }

    /**
     * change HEAD
     * @throws IOException
     */
    public void changeHead() throws IOException {
        File HEAD = new File(Repository.getGitDir() + File.separator + "HEAD");
        FileWriter fileWriter = new FileWriter(HEAD);
        fileWriter.write("ref: "+"refs" + File.separator + "heads" + File.separator + branchName);
        fileWriter.close();
    }

    public boolean exist(){
        String path = Repository.getGitDir() + File.separator + "refs" + File.separator + "heads";
        File currBranchFile = new File(path + File.separator + branchName);
        return currBranchFile.exists();
    }
}
